<?php

namespace App\Http\Controllers\Admin;

use App\Models\BackOrder;
use App\Models\BackOrderItem;
use App\Models\SellOrderItem;
use App\Models\User;
use App\Services\WechatService;
use Illuminate\Http\Request;
use EasyWeChat;

class BackOrderController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('check_admin_login');
    }

    public function index(Request $request)
    {
        $page                         = intval($request->get('page',1));
        $page                         = max($page ,1);
        $page_size                    = intval($request->get('limit',10));
        $no                           = trim($request->get('no'));
        $start_time                   = intval($request->get('start_time'));
        $end_time                     = intval($request->get('end_time'));
        $user_id                      = intval($request->get('user_id'));
        $state                        = intval($request->get('state'));

        $builder = BackOrder::query()->with(['user']);
        if(!empty($no))
        {
            $no = '%'.$no.'%';
            $builder->where('no','like',$no);
        }

        if(!empty($user_id))
        {
            $builder->where('user_id',$user_id);
        }

        if(!empty($start_time))
        {
            $builder->where('created_at','>=',$start_time);
        }

        if(!empty($end_time))
        {
            $builder->where('created_at','<=',$end_time);
        }

        if(!empty($state))
        {
            $builder->where('state',$state);
        }

        $columns = ['id','user_id','no','amount','created_at','pay_type','fee_price','state'];
        $list = $builder->orderBy('id','desc')->paginate($page_size,$columns,'page',$page);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'            => $item->id,
                    'user_id'       => $item->user_id,
                    'no'            => $item->no,
                    'amount'        => $item->amount,
                    'created_at'    => date('Y-m-d H:i:s',$item->created_at),
                    'pay_type'      => $item->pay_type,
                    'fee_price'     => $item->fee_price,
                    'state'         => $item->state,
                    'user_nickname' => $item->user->wechat_nickname,
                    'user_avatar'   => $item->user->wechat_avatar,
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items" => $items
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function show(Request $request)
    {
        $order_id = intval($request->get('order_id'));
        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }
        $order = BackOrder::query()->with(['user'])->where('id',$order_id)->first();
        //dd($order);
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        $back_items = BackOrderItem::query()->where('back_order_id',$order_id)->get();
        $book_ids = [];
        if($back_items->isNotEmpty())
        {
            foreach ($back_items as $v)
            {
                $book_ids[] = $v->book_id;
            }
        }

        $items = SellOrderItem::query()->with(['book'])->where('sell_order_id',$order->sell_order_id)->where('state',2)->get();
        $books = [];
        foreach ($items as $v)
        {
            if(in_array($v->book_id,$book_ids))
            {
                $books[] = [
                    'book_id'               => $v->book_id,
                    'book_title'            => $v->book_title,
                    'book_author'           => $v->book_author,
                    'book_image'            => $v->book_image,
                    'isbn'                  => $v->book->isbn,
                    'state'                 => $v->state,
                    'reason'                => $v->reason,
                ];
            }

        }


        $result = [
            'id'                    => $order->id,
            'no'                    => $order->no,
            'address_receiver'      => $order->address_receiver,
            'address_mobile'        => $order->address_mobile,
            'address_province_name' => $order->address_province_name,
            'address_city_name'     => $order->address_city_name,
            'address_area_name'     => $order->address_area_name,
            'address'               => $order->address,
            'state'                 => $order->state,
            'created_at'            => $order->created_at ? date('Y-m-d H:i:s',$order->created_at) : '',
            'send_time'             => $order->send_time ? date('Y-m-d H:i:s',$order->send_time) : '',
            'pay_at'                => $order->pay_at ? date('Y-m-d H:i:s',$order->pay_at) : '',
            'amount'                => $order->amount,
            'fee_price'             => $order->fee_price,
            'express_delivery_id'   => '中通快递',
            'express_no'            => $order->express_no,
            'user_nickname'         => $order->user->wechat_nickname,
            'user_avatar'           => $order->user->wechat_avatar,
            'books'                 => $books,
        ];
        return $this->ok($result);
    }

    public function send(Request $request)
    {
        $order_id = intval($request->get('order_id'));
        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = BackOrder::query()->where('id',$order_id)->first();
        if(empty($order))
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 1)
        {
            return $this->err(1,200,'','状态错误,无法发货');
        }

        if(!empty($order->express_waybill_id) || $order->is_express)
        {
            return $this->ok(['express_waybill_id' => $order->express_waybill_id,'delivery_id' => $order->express_delivery_id],'操作成功');
        }

        $items = SellOrderItem::query()->where('sell_order_id',$order->sell_order_id)->where('state',2)->get();

        $detail_list = [];
        $goodsName = [];
        $imgUrl = '';
        foreach ($items as $v)
        {
            $goodsName[] = $v->book_title;
            $detail_list[] = [
                'name' => $v->book_title,
                'count' => 1
            ];
            $imgUrl = $v->book_image;
        }

        $user = User::find($order->user_id);
        $openid = $user->wechat_openid;
        //$openid = 'oykEg5WGTi181uPuJUX5jT7jlvr4';

        $delivery_id = 'ZTO';
        $biz_id = 'ZTO531558226398055';
        $data = [
            'order_id'      => $order->no,
            'openid'        => $openid,
            'delivery_id'   => $delivery_id,
            'biz_id'        => $biz_id,
            'custom_remark' => '',
            'sender' => [
                'name'      => '快鱼二手书',
                'tel'       => '',
                'mobile'    => '15888825922',
                'company'   => '',
                'postCode'  => '',
                'country'   => '中国',
                'province'  => '浙江省',
                'city'      => '杭州市',
                'area'      => '余杭区',
                'address'   => '万科未来城',
            ],
            'receiver' => [
                'name'      => $order->address_receiver,
                'tel'       => '',
                'mobile'    => $order->address_mobile,
                'company'   => '',
                'postCode'  => '',
                'country'   => '中国',
                'province'  => $order->address_province_name,
                'city'      => $order->address_city_name,
                'area'      => $order->address_area_name,
                'address'   => $order->address,
            ],
            'cargo' => [
                'count'         => 1,
                'weight'        => 2,
                'space_x'       => 30,
                'space_y'       => 30,
                'space_z'       => 30,
                'detail_list'   => $detail_list
            ],
            'shop' => [
                'wxa_path'      => '/pages/sale/order/tuihui-detail/tuihui-detail?id='.$order_id,
                'img_url'       => 'https://book-shop.oss-cn-hangzhou.aliyuncs.com/images/wuliuzhushou.png',
                'goods_name'    => '退回订单',
                'goods_count'   => $order->amount,
            ],
            'insured' => [
                'use_insured'   => 0,
                'insured_value' => 0
            ],
            'service' => [
                'service_type' => 0,
                'service_name' => '标准快件'
            ]
        ];

        $service = new WechatService();
        $ret = $service->add_order($data);
        if(!empty($ret['waybill_id']))
        {
            $number = count($items);
            $sms = app('easysms');
            try {
                $sms->send($order->address_mobile,[
                    'template' => 'SMS_163055954',
                    'data' => [
                        'name'      => $order->address_receiver,
                        'kuaidi'    => '中通',
                        'number'    => $number,
                    ],
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('aliyun')->getMessage();
                dd($message);
            }

            $officialAccount = EasyWeChat::officialAccount(); // 公众号
            $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
            if(!empty($wechat_user))
            {
                $openid = $wechat_user->openid;

                $first = "您的退回订单，已发货完成"."\r\n"."我们已为您寄回被拒收的{$number}本书，请保持手机畅通，注意查收。"."\r\n";
                $officialAccount->template_message->send([
                    'touser'        => $openid,
                    'template_id'   => 'V6Ls8LGYnGGeEuZIEPlN80DpqzgNU8gtYZbcmr2qbYE',
                    'url'  => '',
                    'miniprogram' => [
                        'appid'     => config('wechat.mini_program.default.app_id'),
                        'path'  => '/pages/sale/order/tuihui-detail/tuihui-detail?id='.$order_id,
                    ],
                    'data' => [
                        'first'     => $first,
                        'keyword1'  => $ret['waybill_id'],
                        'keyword2'  => '中通快递',
                        'keyword3'  => date('Y-m-d H:i:s'),
                        'keyword4'  => $order->address_receiver." ".$order->address_mobile,
                        'keyword5'  => $order->address_province_name.$order->address_city_name.$order->address_area_name.$order->address."\r\n",
                        'remark'    => '点击“详情”可查看订单详情，您可通过物流单号自行查询物流进度。'
                    ],
                ]);
            }


            $order->update([
                'expree_waybill_data'   => json_encode($ret),
                'express_waybill_id'    => $ret['waybill_id'],
                'is_express'            => 1,
                'express_no'            => $ret['waybill_id'],
                'state'                 => 2,
                'send_time'             => $this->time,
            ]);
            return $this->ok(['express_waybill_id' => $ret['waybill_id'],'delivery_id' => $delivery_id],'操作成功');
        }

        $order->update([
            'expree_waybill_data_error' => json_encode($ret),
        ]);
        return $this->err(1,200,'','操作失败');
    }
}
